package com.spzx.product.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.product.service.SkuStockService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class ProductReceiver {

    @Autowired
    private SkuStockService skuStockService;

    @SneakyThrows//忽略编译时异常
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT),//默认持久化
            key = {MqConst.ROUTING_UNLOCK},
            value = @Queue(value = MqConst.QUEUE_UNLOCK, durable = "true")
    ))
    public void unlock(String orderNo, Message message, Channel channel) {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
//        String orderNo = new String(message.getBody());
            log.info("监听解锁库存消息:{}", orderNo);
            skuStockService.unlock(orderNo);//解锁库存
            //手动确认消息 false 只确认当前消息 true 批量确认当前通道下的所有消费者获得的消息
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            //手动拒绝消息 true 可以让队列重新入队 false 不能重新入队
            channel.basicNack(deliveryTag, false, true);
            throw new ServiceException("解锁库存失败");
        }
    }

    /**
     * 扣减库存
     * @param orderNo  订单号
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT, durable = "true"),
            key = {MqConst.ROUTING_MINUS},
            value = @Queue(value = MqConst.QUEUE_MINUS, durable = "true")
    ))
    public void minus(String orderNo, Channel channel, Message message) {
        //业务处理
        if (StringUtils.isNotEmpty(orderNo)){
            log.info("监听减库存消息：{}", orderNo);
            //扣减库存
            skuStockService.minus(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
